package com.gouwudai.gobbs.common;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class EncodeString 
{
    private static final Log logger = LogFactory.getLog(EncodeString.class);   
    
    /**
     * 将内容按照HTML编码
     * @param src
     * @return
     */
	public static String htmlEncoder(String src)
    {
        if(src == null || src.equals(""))
        {
            return "";
        } 
        else
        {
            src = src.replace("<", "&lt;");
            src = src.replace(">", "&gt;");
            src = src.replace("\"", "&quot;");
            src = src.replace("'", "&#039;");
            src = src.replace(" ", " &nbsp;");
            src = src.replace("\r\n", "<br/>");
            src = src.replace("\r", "<br/>");
            src = src.replace("\n", "<br/>");
            return src;
        }
    }
	
    /**
     * 将内容按照HTML编码,允许HTML代码，只对脚本进行处理
     * @param src
     * @return
     */
	public static String htmlEncoderEx(String src)
    {
        if(src == null || src.equals(""))
        {
            return "";
        } 
        else
        {
        	src = ubbPattern(src,"\\<script\\>(.*?)\\</script>\\>","");	//将所有脚本内容清空
            return src;
        }
    }	
	
	/**
     * 转换为XML编码
     */
    public static String xmlEncoder(String src){
        if(src == null || src.equals(""))
        {
            return "";
        } else
        {
            String xmlencode = src;
            xmlencode = xmlencode.replaceAll("&", "&amp;");
            xmlencode = xmlencode.replaceAll("<", "&lt;");
            xmlencode = xmlencode.replaceAll(">", "&gt;");
            xmlencode = xmlencode.replaceAll("\"", "&quot;");
            xmlencode = xmlencode.replaceAll("'", "&acute;");
            return xmlencode;
        }
    }	
    
    /**
     * 解析UBB内容
     * @param str
     * @return
     */
    public static String ubbEncoder(String str){
        if(str==null || str.equals("")){
            return "";
        }
        if(logger.isDebugEnabled())
        {
            logger.debug("UBB原内容:"+str);
        }
        str = ubbPattern(str,"\\[center\\](.*?)\\[/center\\]","<center>$1</center>");
        str = ubbPattern(str,"\\[b\\](.*?)\\[/b\\]","<strong>$1</strong>");
        str = ubbPattern(str,"\\[i\\](.*?)\\[/i\\]","<emg>$1</em>");
        str = ubbPattern(str, "\\[color=(.*?)\\](.*?)\\[/color\\]","<span style=color:$1>$2</span>");
        str = ubbPattern(str, "\\[face_(\\d*)\\]","<img src=\"images/face/$1.gif\">");
        str = ubbPattern(str, "\\[img\\](.*?)\\[/img\\]","<a href=\"$1\" target=\"_blank\"><img " +
            " onload=\"javascript:if(this.width > screen.width-350){this.width = screen.width-350};\" " + 
            " onerror=\"javascript:this.src='images/imgErr.gif'\" src=\"$1\" border=\"0\" /></a>");
        if(logger.isDebugEnabled())
        {
            logger.debug("[IMG]解析后:"+str);
        }        
        str = ubbPattern(str, "\\[url\\](.*?)\\[/url\\]","<a href=\"$1\" target=\"_blank\">$1</a>");
        if(logger.isDebugEnabled())
        {
            logger.debug("[URL]解析后:"+str);
        }
        str = ubbPattern(str, "\\[url=(.*?)\\](.*?)\\[/url\\]","<a href=\"$1\" target=\"_blank\">$2</a>");
        str = ubbPattern(str, "\\[size=*([\\d]*)\\](.*?)\\[/size\\]","<span style=\"font-size: $1px;\">$2</span>");
        str = ubbPattern(str,"\\[quote\\](.*?)\\[/quote\\]","<table align=center bgcolor=\"#BAD5EF\" width=\"98%\" border=0 cellpadding=4 cellspacing=1>" +
                                "<tr><td bgcolor=\"#E6EEF7\" height=\"25\"  style=\"font-size: 12px\"><strong>以下内容为引用内容</strong>：</td></tr><tr><td bgcolor=\"#ffffff\" style=\"font-size: 12px\">$1</td></tr></table>");
        
        str = ubbPattern(str,"\\[quote=(.*?)\\](.*?)\\[/quote\\]","<table align=center bgcolor=\"#BAD5EF\" width=\"98%\" border=0 cellpadding=4 cellspacing=1>" +
        "<tr><td bgcolor=\"#E6EEF7\" height=\"25\"  style=\"font-size: 12px\"><strong>$1 说：</strong></td></tr><tr><td bgcolor=\"#ffffff\" style=\"font-size: 12px\">$2</td></tr></table>");
        
        StringBuffer sb = new StringBuffer("");
        sb.append("<object codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" );
        sb.append(" height=400 width=500 classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000>");
        sb.append("<param name=\"movie\" value=\"$1\">");
        sb.append("<param name=\"menu\" value=\"false\">");
        sb.append("<embed src=\"$1\" menu=false quality=high ");
        sb.append(" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\"" );
        sb.append(" type=\"application/x-shockwave-flash\" width=\"500\" height=\"400\"></embed></object>");
        //UBB多媒体部分开始
        str = ubbPattern(str, "\\[flash\\](.*?)\\[/flash\\]","<a href=\"$1\" target='_blank'>[全屏欣赏]</a><br>" + sb.toString());
       
        sb.delete(0,sb.length());
        
        sb.append("<object codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" );
        sb.append(" height=$2 width=$1 classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000>");
        sb.append("<param name=\"movie\" value=\"$3\">");
        sb.append("<param name=\"menu\" value=\"false\">");
        sb.append("<embed src=\"$3\" menu=\"false\" quality=\"high\"");
        sb.append(" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\"" );
        sb.append(" type=\"application/x-shockwave-flash\" width=\"$1\" height=\"$2\"></embed></object>");
        
        str = ubbPattern(str, "\\[flash=*([\\d]*),*([\\d]*)\\](.*?)\\[/flash\\]","<a href=\"$3\" TARGET=_blank>[全屏欣赏]</a><br>" + sb.toString());
        sb.delete(0,sb.length());  
        
        str = ubbPattern(str, "\\[real\\](.*?)\\[/real\\]","<OBJECT classid=clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA class=OBJECT id=RAOCX width=\"450\" height=\"350\"><PARAM NAME=SRC VALUE=$1><PARAM NAME=CONSOLE VALUE=Clip1><PARAM NAME=CONTROLS VALUE=imagewindow><PARAM NAME=AUTOSTART VALUE=true></OBJECT><br><OBJECT classid=CLSID:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA height=35 id=video2 width=450><PARAM NAME=SRC VALUE=$1><PARAM NAME=AUTOSTART VALUE=-1><PARAM NAME=CONTROLS VALUE=controlpanel><PARAM NAME=CONSOLE VALUE=Clip1></OBJECT>");
        str = ubbPattern(str, "\\[real=*([\\d]*),*([\\d]*)\\](.*?)\\[/real\\]","<OBJECT classid=clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA class=OBJECT id=RAOCX width=\"$1\" height=\"$2\"><PARAM NAME=SRC VALUE=$3><PARAM NAME=CONSOLE VALUE=Clip1><PARAM NAME=CONTROLS VALUE=imagewindow><PARAM NAME=AUTOSTART VALUE=true></OBJECT><br><OBJECT classid=CLSID:CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA height=35 id=video2 width=450><PARAM NAME=SRC VALUE=$3><PARAM NAME=AUTOSTART VALUE=-1><PARAM NAME=CONTROLS VALUE=controlpanel><PARAM NAME=CONSOLE VALUE=Clip1></OBJECT>");
        str = ubbPattern(str, "\\[video\\](.*?)\\[/video\\]","<object align=middle classid=CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95 class=OBJECT id=MediaPlayer width=\"450\" height=\"300\"><param name=\"loop\" value=\"true\"><param name=ShowStatusBar value=-1><param name=Filename value=\"$1\"><embed type=application/x-oleobject codebase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701 flename=\"mp\" src=\"$1\" width=\"450\" height=\"300\"></embed></object>");
        str = ubbPattern(str, "\\[video=*([\\d]*),*([\\d]*)\\](.*?)\\[/video\\]","<object align=middle classid=CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95 class=OBJECT id=MediaPlayer width=\"$1\" height=\"$2\"><param name=\"loop\" value=\"true\"><param name=ShowStatusBar value=-1><param name=Filename value=\"$3\"><embed type=application/x-oleobject codebase=http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701 flename=\"mp\" src=\"$3\" width=\"$1\" height=\"$2\"></embed></object>");
        // UBB多媒体部分结束
//取消Url自动识别、图片自动识别          
//        if(ubbImg){
//            str = ubbPattern(str,"((http|https|ftp|rtsp|mms):(//|\\\\)([\\w\\.\\:/\\?\\=%&_-]+(gif|jpg|jpeg|bmp|png)))",
//            "<a href=\"$1\" target=\"_blank\"><img onload=\"javascript:if(this.width > screen.width-350){this.width = screen.width-350};\" " +
//            " onerror=\"javascript:this.src='images/imgErr.gif'\" src=\"$1\" border=\"0\"></a>");
//
//        }
//        if(ubbUrl){
//               str = ubbPattern(str,"((http|https|ftp|rtsp|mms):(//|\\\\)([\\w\\.\\:/\\?\\=%&_-]+))",
//               "<a target=\"_blank\" href=\"$1\">$1</a>");
//               //str = ubbPattern(str,"^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$" ,
//                        //"<a target=\"_blank\" href=\"$1\">$1</a>");
//        }
       
        
        str = htmlRun(str);
        return str;
    }  
    
    /**
     * 标记可运行代码
     * @param src
     * @return
     */
    private static String htmlRun(String src)
    {
        if(src == null)
        {
            return "";
        } else
        {
            String str = "";
            str = matcherCodeColor(src, "\\[code\\](.*?)\\[/code]");
            str = ubbPattern(str, "\\[code\\](.*?)\\[/code]", "<table align=center bgcolor=\"#BAD5EF\" width=\"98%\" border=0 cellpadding=4 cellspacing=1><form><tr><td bgcolor=\"#E6EEF7\" height=\"25\"  style=\"font-size: 12px\">程序代码：</td></tr><tr><td bgcolor=\"#ffffff\" style=\"font-size: 12px\"><code>$1</code></td></tr></form></table>");
            return str;
        }
    } 
    
    /**
     * 代码内容的色彩替换
     * @param str
     * @param cp
     * @param s
     * @return
     */    
    public static String matcherCodeColor(String str, String cp){
        if(str==null || str.equals("")){
            return "";
        }
        String txt = new String();
        if(str!=null && !str.equals("")){
            txt = str;
            Pattern p = Pattern.compile(cp,2); //参数2表示大小写不区分
            Matcher m = p.matcher(txt);
            StringBuffer sb = new StringBuffer();
            boolean result = m.find();
            String temp = "";
            //使用循环将句子里所有匹配的内容找出并替换再将内容加到sb里
            for(; result; result = m.find())
            {
                temp = m.group();
                temp = codeColor(temp);
                m.appendReplacement(sb, temp);
            }
            //最后调用appendTail()方法将最后一次匹配后的剩余字符串加到sb里；
            m.appendTail(sb);
            txt = String.valueOf(sb);
        }else{
            txt = "";
        }
        return txt;       
    }    
	
    /**
     * 代码的UBB编码
     */
    public static String codeColor(String str){

        if(str==null) return "";
        str = str.replaceAll(" ","");
        str = ubbPattern(str, "&quot;(.*?)&quot;","<span style=color:#2A00FF;>&quot;$1&quot;</span>");
        str = ubbPattern(str, "\\/\\*(.*?)\\*/","<span style=color:#3F7F5F;>/*$1*/</span>");
        
        //str = ubbPattern(str, "http://(.*?)<br/>","<span style=color:#3F7F5F;>http://$1</span><br/>");
        str = ubbPattern(str, "\\/\\/(.*?)\\<br/>","<span style=color:#3F7F5F;>//$1</span><br/>");
        
        //str = ubbPattern(str, "&lt;(.*?)&gt;","<span style=color:#006600;>&lt;$1&gt;</span>");
        //str = ubbPattern(str, "&lt;(.*?)/&gt;","<span style=color:#006600;>&lt;$1/&gt;</span>");
        str = ubbPattern(str,"private&nbsp;","<span style=\"color:#7F0055; font-weight: bold;\">private&nbsp;</span>");
        str = ubbPattern(str,"protected&nbsp;","<span style=\"color:#7F0055; font-weight: bold;\">protected&nbsp;</span>");
        str = ubbPattern(str,"public&nbsp;","<span style=\"color:#7F0055; font-weight: bold;\">public&nbsp;</span>");
        str = ubbPattern(str,"static&nbsp;","<span style=\"color:#7F0055; font-weight: bold;\">static&nbsp;</span>");
        str = ubbPattern(str,"return&nbsp;","<span style=\"color:#7F0055; font-weight: bold;\">return&nbsp;</span>");
        str = ubbPattern(str,"try","<span style=\"color:#7F0055; font-weight: bold;\">try</span>");
        str = ubbPattern(str,"catch","<span style=\"color:#7F0055; font-weight: bold;\">catch</span>");
        str = ubbPattern(str,"finally","<span style=\"color:#7F0055; font-weight: bold;\">finally</span>");
        str = ubbPattern(str,"package","<span style=\"color:#7F0055; font-weight: bold;\">package</span>");
         
        
        str = ubbPattern(str,"null","<span style=\"color:#7F0055; font-weight: bold;\">null</span>");
        str = ubbPattern(str,"short&nbsp;","<span style=\"color:#7F0055; font-weight: bold;\">short&nbsp;</span>");
        str = ubbPattern(str,"int&nbsp;","<span style=\"color:#7F0055; font-weight: bold;\">int&nbsp;</span>");
        str = ubbPattern(str,"double&nbsp;","<span style=\"color:#7F0055; font-weight: bold;\">double&nbsp;</span>");
        str = ubbPattern(str,"byte&nbsp;","<span style=\"color:#7F0055; font-weight: bold;\">byte&nbsp;</span>");
        str = ubbPattern(str,"long&nbsp;","<span style=\"color:#7F0055; font-weight: bold;\">long&nbsp;</span>");
        str = ubbPattern(str,"final&nbsp;","<span style=\"color:#7F0055; font-weight: bold;\">final&nbsp;</span>");
        str = ubbPattern(str,"new&nbsp;","<span style=\"color:#7F0055; font-weight: bold;\">new&nbsp;</span>");
        str = ubbPattern(str,"false","<span style=\"color:#7F0055; font-weight: bold;\">false</span>");
        str = ubbPattern(str,"true","<span style=\"color:#7F0055; font-weight: bold;\">true</span>");
 
        
        str = ubbPattern(str,"while\\(","<span style=\"color:#7F0055; font-weight: bold;\">while</span>(");
        str = ubbPattern(str,"for\\(","<span style=\"color:#7F0055; font-weight: bold;\">for</span>(");
        str = ubbPattern(str,"switch","<span style=\"color:#7F0055; font-weight: bold;\">switch</span>");
        str = ubbPattern(str,"if\\(","<span style=\"color:#7F0055; font-weight: bold;\">if</span>(");
        str = ubbPattern(str,"else","<span style=\"color:#7F0055; font-weight: bold;\">else</span>");
        str = ubbPattern(str,"this\\.","<span style=\"color:#7F0055; font-weight: bold;\">this</span>.");
        str = ubbPattern(str,"function\\(","<span style=\"color:#7F0055; font-weight: bold;\">function</span>(");
        str = ubbPattern(str,"document.","<span style=\"color:#7F0055; font-weight: bold;\">document</span>.");
        
        
        return str; 
    }
    
    /**
     * 正则匹配并完成替换过程
     * @param str 要检索的字符串
     * @param cp 正则匹配条件字符串
     * @param mc 要替换成的字符串
     * @return
     */
    public static String ubbPattern(String str, String cp, String mc)
    {
        if(str==null || str.equals("")){
            return "";
        }
        String txt = new String();
        txt = str;
        if(str!=null && !str.equals("")){
            txt = str;
            Pattern p = Pattern.compile(cp,2); //参数2表示大小写不区分
            Matcher m = p.matcher(txt);
            txt = m.replaceAll(mc);
        }else{
            txt = "";
        }
        return txt;       
    }    
	
    /**
     * 循环找出匹配内容
     * @param str
     * @param cp
     * @param s
     * @return
     * 2005-12-11 18:45:25 Made In GamVan
     * com.gamvan.tools
     */
    public static String matcherStr(String str, String cp, String s){
        if(str==null || str.equals("")){
            return "";
        }
        String txt = new String();
        txt = str;
        if(str!=null && !str.equals("")){
            txt = str;
            Pattern p = Pattern.compile(cp,2); //参数2表示大小写不区分
            Matcher m = p.matcher(txt);
            StringBuffer sb = new StringBuffer();
            int i=0;
            boolean result = m.find();
            //使用循环将句子里所有匹配的内容找出并替换再将内容加到sb里
            while(result) {
                i++;
                sb.append(m.group());
                sb.append(s);
                //继续查找下一个匹配对象
                result = m.find();
            }
            txt = String.valueOf(sb);
        }else{
            txt = "";
        }
        return txt;       
    }
    
    /**
     * 指定第几次匹配才执行替换
     * @param str
     * @param cp
     * @param s
     * @param loop 指定第几次, 0表示循环所有匹配内
     * @return
     * 2005-12-11 18:46:30 Made In GamVan
     * com.gamvan.tools
     */
    public static String matcherStr(String str, String cp, String s, int loop){
        if(str==null || str.equals("")){
            return "";
        }
        String txt = new String();
        txt = str;
        if(str!=null && !str.equals("")){
            txt = str;
            Pattern p = Pattern.compile(cp,2); //参数2表示大小写不区分
            Matcher m = p.matcher(txt);
            StringBuffer sb = new StringBuffer();
            int i=0;
            boolean result = m.find();
            //使用循环将句子里所有匹配的内容找出并替换再将内容加到sb里
            while(result) {
                i++;
                if(loop==i){
	                sb.append(m.group());
	                sb.append(s);
                }else if(loop==0){
	                sb.append(m.group());
	                sb.append(s);
	                //继续查找下一个匹配对象
	                result = m.find();
                }else{
                    //继续查找下一个匹配对象
                    result = m.find();
                }
            }    
            txt = String.valueOf(sb);
        }else{
            txt = "";
        }
        return txt;       
    }
    
    public static List matcherList(String str, String cp)
    {
        if(str == null || str.equals(""))
            return null;
        List list = new ArrayList();
        String txt = new String();
        txt = str;
        if(str != null && !str.equals(""))
        {
            txt = str;
            Pattern p = Pattern.compile(cp, 2);
            Matcher m = p.matcher(txt);
            for(boolean result = m.find(); result; result = m.find())
                list.add(m.group());

        }
        return list;
    }  	

}
